package main

import (
    "encoding/json"
    "fmt"
    "github.com/micro/go-micro"
    "github.com/micro/go-micro/broker"
    userProto "hello/proto/user"
)

const topic = "user.registered"

func main() {
    srv := micro.NewService(
        micro.Name("go.micro.srv.email"),
        micro.Version("latest"),
    )
    srv.Init()

    pubSub := srv.Server().Options().Broker
    if err := pubSub.Connect(); err != nil {
        fmt.Errorf("broker connect error: %v\n", err)
    }

    // 订阅消息
    _, err := pubSub.Subscribe(topic, func(pub broker.Event) error {
        var user *userProto.User
        if err := json.Unmarshal(pub.Message().Body, &user); err != nil {
            fmt.Errorf("process message failed: %v\n", err)
            return err
        }
        fmt.Printf("[User Registered]: %v\n", user)
        go sendEmail(user)
        return nil
    })

    if err != nil {
        fmt.Printf("sub error: %v\n", err)
    }

    if err := srv.Run(); err != nil {
        fmt.Errorf("srv run error: %v\n", err)
    }
}

func sendEmail(user *userProto.User) error {
    fmt.Printf("[SENDING A EMAIL TO %s...]\n", user.Name)
    return nil
}